﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;

namespace __Ts.Core.Plugin
{
    public class PluginManager
    {
        private Dictionary<string, PluginDomain> _plugins;
        private string[] _ports;

        /// <summary>
        /// 模块存放的目录
        /// </summary>
        public string ModulesDirectory = System.AppDomain.CurrentDomain.BaseDirectory + "Modules";

        /// <summary>
        /// 配置文件存放的目录
        /// </summary>
        public string ConfigsDirectory = System.AppDomain.CurrentDomain.BaseDirectory + "Configs";

        /// <summary>
        /// 监听端口
        /// </summary>
        public string[] Ports
        {
            get
            {
                if (_ports == null || _ports.Length < 1)
                {
                    StringBuilder sb = new StringBuilder();
                    DirectoryInfo dir = new DirectoryInfo(ConfigsDirectory);
                    string name = string.Empty;
                    foreach (FileInfo file in dir.GetFiles("*.xml"))
                    {
                        name = Path.GetFileNameWithoutExtension(file.Name);
                        if (Regex.IsMatch(name, @"\d+"))
                        {
                            if (sb.Length > 0)
                                sb.Append(",");
                            sb.Append(name);
                        }
                    }
                    _ports = sb.ToString().Split(',');
                }
                return _ports;
            }
        }

        public PluginManager()
        {
            _plugins = new Dictionary<string, PluginDomain>();

            FileInfo[] fs = new DirectoryInfo(ModulesDirectory).GetFiles("*.dll", SearchOption.AllDirectories);
            foreach (FileInfo file in fs)
            {
                Load(file.FullName);
            }
        }

        private bool Load(string assemblyPath)
        {
            // 检验命名是否规范
            if (!Regex.IsMatch(Path.GetFileNameWithoutExtension(assemblyPath), @"^\w+(?:_\d){3}$"))
                return false;

            PluginDomain domain = new PluginDomain(assemblyPath);
            _plugins.Add(domain.GetPlugin().PluginKey, domain);
            return true;
        }

        public PluginDomain GetPluginDomain(string pluginKey)
        {
            if (_plugins.ContainsKey(pluginKey))
                return _plugins[pluginKey] as PluginDomain;
            return null;
        }
    }
}
